package ca.ubc.eece310.project;

/**
 * EECE 310 Term Project Fall 2009
 * @author Matthew Fong, Herman Lee, Scott Pearson
 */

import java.text.DecimalFormat;

import javax.swing.table.AbstractTableModel;

public class ProcessTableModel extends AbstractTableModel {

	/**
	 * OVERVIEW: Datatype containing processes, their PIDs and their upload and
	 * download traffic	 
	 * Rep-Invariant: N/A
	 * AF(c): c.data[i][j] | 0 <= i < c.elements.size
	 * 		  			   | 0 <= j < numLines
	 */

	private static final long serialVersionUID = 3955763864584512372L;

	private String[] columnNames = { "Process", "PID", "Download rate", "Upload rate" };
	private Object[][] data;

	// CONSTRUCTOR
	public ProcessTableModel() {
		/**
		 * MODIFIES: data EFFECTS: Initializes the data array and fills it
		 */
		data = new Object[RunningProcess.RunningProcesses.size()][RunningProcess.numFields];
		updateTable();
	}

	@Override
	public int getColumnCount() {
		/**
		 * EFFECTS: Returns the number of columns
		 */
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		/**
		 * EFFECTS: Returns the length of the data array
		 */
		return data.length;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		/**
		 * REQUIRES: 0 < rowIndex < data.length, 0 < columnIndex <
		 * columnNames.length EFFECTS: Returns the Object in
		 * data[rowIndex][columnIndex]
		 */
		return data[rowIndex][columnIndex];
	}

	public String getColumnName(int col) {
		/**
		 * EFFECTS: Returns the column name;
		 */
		return columnNames[col];
	}

	public void updateTable() {
		/**
		 * MODIFIES: data EFFECTS: Gets all the information from
		 * RunningProcess.RunningProcesses and stores it into data under the
		 * appropriate columns
		 */
		DecimalFormat format = new DecimalFormat("##.###");
		data = new Object[RunningProcess.RunningProcesses.size()][RunningProcess.numFields];
		for (int i = 0; i < RunningProcess.RunningProcesses.size(); i++) {
			data[i][0] = RunningProcess.RunningProcesses.get(i)
					.getProcessName();
			data[i][1] = RunningProcess.RunningProcesses.get(i).getPID();
			data[i][2] = format.format(RunningProcess.RunningProcesses.get(i)
					.getDown());
			data[i][3] = format.format(RunningProcess.RunningProcesses.get(i)
					.getUp());
		}
	}

	public boolean repOK() {
		/**
		 * EFFECTS: Returns true if the rep invariant holds for this
		 * 			else returns false
		 */
		return true;
	}
	
	public String toString() {
		/**
		 * EFFECTS: Returns a String representation
		 */
		String s = new String();
		s = columnNames[0] + "\t" + columnNames[1] + "\t" + columnNames[2] + "\t" + columnNames[3] + "\n";
		for(int i=0; i<data.length; i++) {
			s = s + data[i][0] + "\t" + data[i][1] + "\t" + data[i][2] + "\t" + data[i][3] + "\n";
		}
		return s;
	}
}
